package com.roads.screen.controller;

import com.roads.common.constant.Constants;
import com.roads.common.core.controller.BaseController;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.utils.SecurityUtils;
import com.roads.common.utils.StringUtils;
import com.roads.engineering.constant.PaymentConstant;
import com.roads.engineering.domain.summary.SummaryIpc;
import com.roads.engineering.service.ISummaryService;
import com.roads.project.domain.ProBoq;
import com.roads.project.domain.ProInstitution;
import com.roads.project.domain.ProPaymentItems;
import com.roads.project.domain.ProPeriod;
import com.roads.project.service.IProBoqService;
import com.roads.project.service.IProInstitutionService;
import com.roads.project.service.IProPaymentItemsService;
import com.roads.project.service.IProPeriodService;
import com.roads.screen.service.IScreen4DataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 可视化大屏4数据Controller
 *
 * @author nhp
 * @date 2023-10-10
 */
@RestController
@RequestMapping("/screen/screen4/data")
public class Screen4DataController extends BaseController {

    @Autowired
    private IScreen4DataService service;

    @Autowired
    private IProInstitutionService institutionService;

    @Autowired
    private ISummaryService summaryService;

    @Autowired
    private IProPaymentItemsService paymentItemsService;

    @Autowired
    private IProPeriodService periodService;

    @Autowired
    private IProBoqService boqService;

    /**
     * 可视化大屏4 getData2
     *
     * @param projectId 项目ID
     * @return 结果
     */
    @RequestMapping("/getData2/{projectId}")
    public AjaxResult getData2(@PathVariable("projectId") Integer projectId) {
        AjaxResult ajaxResult = new AjaxResult();
        String userName = getUsername();
        // 获取所有期次
        boolean isAdmin = SecurityUtils.isAdmin(getUserId());
        List<ProInstitution> bids = null;
        if (isAdmin) {
            userName = "";
            bids = institutionService.selectBidListByProjectId(projectId);
        } else {
            bids = institutionService.selectBidListByUserAndProjectId(projectId, userName);
        }
        List<String> periods = service.selectBidPeriodsByUserAndProjectId(userName, projectId);
        List<Integer> currentEndTotalList = new ArrayList<>();
        List<Integer> currentTotalList = new ArrayList<>();
        for (String period : periods) {
            BigDecimal currentEndTotal = BigDecimal.ZERO;
            BigDecimal currentTotal = BigDecimal.ZERO;
            for (ProInstitution bid : bids) {
                if (Constants.NO.equals(bid.getIsCount())) {
                    continue;
                }
                String summaryUser = summaryService.getSummaryLastUser(bid.getInnerCode(), period);
                if (StringUtils.isNotEmpty(summaryUser)) {
                    SummaryIpc ipc = summaryService.getItemByBidAndPeriodAndItemCode(bid.getInnerCode(), period, summaryUser, PaymentConstant.ZQZFZS_ZJ);
                    if (StringUtils.isNotNull(ipc)) {
                        BigDecimal summaryCurrentEnd = ipc.getCurrentEndPeriodTotal() == null ? BigDecimal.ZERO : ipc.getCurrentEndPeriodTotal();
                        currentEndTotal = currentEndTotal.add(summaryCurrentEnd);
                        BigDecimal summaryCurrent = ipc.getCurrentPeriodTotal() == null ? BigDecimal.ZERO : ipc.getCurrentPeriodTotal();
                        currentTotal = currentTotal.add(summaryCurrent);
                    }
                }
            }
            int intCurrentEndValue = currentEndTotal.divide(BigDecimal.valueOf(10000), 0, BigDecimal.ROUND_HALF_UP).intValue();
            currentEndTotalList.add(intCurrentEndValue);
            int intCurrentValue = currentTotal.divide(BigDecimal.valueOf(10000), 0, BigDecimal.ROUND_HALF_UP).intValue();
            if (intCurrentValue != 0) {
                currentTotalList.add(intCurrentValue);
            }
        }
        ajaxResult.put("periods", periods);
        ajaxResult.put("currentEndTotalList", currentEndTotalList);
        ajaxResult.put("currentTotalList", currentTotalList);
        return ajaxResult;
    }

    /**
     * 可视化大屏4 getData3
     *
     * @param projectId 项目ID
     * @return 结果
     */
    @RequestMapping("/getData3/{projectId}")
    public AjaxResult getData3(@PathVariable("projectId") Integer projectId) {
        AjaxResult ajaxResult = new AjaxResult();
        // 获取支付项目
        ProPaymentItems search = new ProPaymentItems();
        search.setProjectId(projectId);
        List<ProPaymentItems> proPaymentItems = paymentItemsService.selectModelList(search);
        List<String> items = new ArrayList<>();
        List<String> itemNames = new ArrayList<>();
        for (ProPaymentItems paymentItem : proPaymentItems) {
            if (paymentItem.getComputeMode() == 1) {
                items.add(paymentItem.getItemCode());
                itemNames.add(paymentItem.getItemName());
            }
        }
        List<BigDecimal> percentages = new ArrayList<>();
        boolean isAdmin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        List<ProInstitution> bids = null;
        if (isAdmin) {
            bids = institutionService.selectBidListByProjectId(projectId);
        } else {
            bids = institutionService.selectBidListByUserAndProjectId(projectId, getUsername());
        }
        for (String itemCode : items) {
            BigDecimal contractTotal = BigDecimal.ZERO;
            BigDecimal currentEndTotal = BigDecimal.ZERO;
            for (ProInstitution bid : bids) {
                if (Constants.NO.equals(bid.getIsCount())) {
                    continue;
                }
                ProPeriod period = periodService.getLastLockPeriod(bid.getInnerCode());
                if (StringUtils.isNotNull(period)) {
                    String summaryUser = summaryService.getSummaryLastUser(bid.getInnerCode(), period.getPeriodName());
                    if (StringUtils.isNotEmpty(summaryUser)) {
                        SummaryIpc ipc = summaryService.getItemByBidAndPeriodAndItemCode(bid.getInnerCode(), period.getPeriodName(), summaryUser, itemCode);
                        if (StringUtils.isNotNull(ipc)) {
                            BigDecimal bidHtJe = ipc.getTotal() == null ? BigDecimal.ZERO : ipc.getTotal();
                            BigDecimal bidBqmJe = ipc.getCurrentEndPeriodTotal() == null ? BigDecimal.ZERO : ipc.getCurrentEndPeriodTotal();
                            contractTotal = contractTotal.add(bidHtJe);
                            currentEndTotal = currentEndTotal.add(bidBqmJe);
                        }
                    }
                }
            }
            if (contractTotal.compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal percentage = currentEndTotal.divide(contractTotal, 2, BigDecimal.ROUND_HALF_UP);
                percentages.add(percentage);
            } else {
                percentages.add(BigDecimal.ZERO);
            }
        }
        Collections.reverse(itemNames);
        Collections.reverse(percentages);
        ajaxResult.put("itemNames", itemNames);
        ajaxResult.put("percentages", percentages);
        return ajaxResult;
    }

    /**
     * 可视化大屏4 getData5
     *
     * @param projectId 项目ID
     * @return 结果
     */
    @RequestMapping("/getData5/{projectId}")
    public AjaxResult getData5(@PathVariable("projectId") Integer projectId) {
        AjaxResult ajaxResult = new AjaxResult();
        boolean isAdmin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        List<ProInstitution> bids = null;
        if (isAdmin) {
            bids = institutionService.selectBidListByProjectId(projectId);
        } else {
            bids = institutionService.selectBidListByUserAndProjectId(projectId, getUsername());
        }
        // 获取支付项目
        ProPaymentItems search = new ProPaymentItems();
        search.setProjectId(projectId);
        List<ProPaymentItems> proPaymentItems = paymentItemsService.selectModelList(search);
        List<String> items = new ArrayList<>();
        for (ProPaymentItems paymentItem : proPaymentItems) {
            if (paymentItem.getComputeMode() == 1) {
                items.add(paymentItem.getItemCode());
            }
        }
        List<Map<Object, Object>> mapList = new ArrayList<>();
        for (ProPaymentItems item : proPaymentItems) {
            if (item.getComputeMode() == 1) {
                String code = item.getItemCode();
                String name = item.getItemName();
                BigDecimal total = BigDecimal.ZERO;
                for (ProInstitution bid : bids) {
                    if (Constants.NO.equals(bid.getIsCount())) {
                        continue;
                    }
                    ProBoq boq = boqService.selectProBoqByCode(bid.getInnerCode(), code);
                    if (StringUtils.isNotNull(boq)) {
                        BigDecimal contractTotal = boq.getTotal() == null ? BigDecimal.ZERO : boq.getTotal();
                        total = total.add(contractTotal);
                    }
                }
                int intValue = total.divide(BigDecimal.valueOf(10000), 0, BigDecimal.ROUND_HALF_UP).intValue();
                Map<Object, Object> map = new HashMap();
                map.put("name", name);
                map.put("value", intValue);
                mapList.add(map);
            }
        }
        ajaxResult.put("mapList", mapList);
        return ajaxResult;
    }

    /**
     * 可视化大屏4 getLabourStaff
     *
     * @param projectId 项目ID
     * @return 结果
     */
    @RequestMapping("/getLabourStaff/{projectId}")
    public AjaxResult getLabourStaff(@PathVariable("projectId") Integer projectId) {
        AjaxResult ajaxResult = new AjaxResult();
        boolean isAdmin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        String userName = "";
        if (!isAdmin) {
            userName = getUsername();
        }
        // 在场人数
        int count = service.getLabourStaffPresenceCount(userName, projectId);
        String formatCount = String.format("%05d", count);
        // 本月进场人数
        int enterCount = service.getLabourStaffEnterCount(userName, projectId);
        String formatEnterCount = String.format("%05d", enterCount);
        // 本月离场人数
        int exitCount = service.getLabourStaffExitCount(userName, projectId);
        String formatExitCount = String.format("%05d", exitCount);
        List<Map<String, Object>> postList = service.getLabourStaffGroupPost(userName, projectId);
        // 获取劳务工工期
        List<String> salaryDateList = service.selectSalaryDateByUserAndProjectId(userName, projectId);
        List<Integer> totalList = new ArrayList<>();
        List<Integer> accumulateTotalList = new ArrayList<>();
        int accumulateTotal = 0;
        for (String salaryDate : salaryDateList) {
            BigDecimal total = service.getLabourStaffSalaryBySalaryDateAndUserAndProjectId(userName, projectId, salaryDate);
            total = total == null ? BigDecimal.ZERO : total;
            total = total.setScale(0, BigDecimal.ROUND_HALF_UP);
            accumulateTotal += total.intValue();
            totalList.add(total.intValue());
            accumulateTotalList.add(accumulateTotal);
        }
        ajaxResult.put("staffCount", formatCount);
        ajaxResult.put("enterCount", formatEnterCount);
        ajaxResult.put("exitCount", formatExitCount);
        ajaxResult.put("postGroup", postList);
        ajaxResult.put("salaryDate", salaryDateList);
        ajaxResult.put("totalList", totalList);
        ajaxResult.put("accumulateTotalList", accumulateTotalList);
        return ajaxResult;
    }

}
